import axios from "axios";
import { Message } from "element-ui";

const instance = axios.create({
  baseURL: process.env.BASE_API,
  timeout: 1000*60,
  responseType: "json",
  withCredentials: true,
  headers: {
    "Content-Type": "application/json;charset=utf-8"
  }
})

// create an axios instance
instance.interceptors.request.use(
  config => {
    // 判断是否存在token，如果存在的话，则每个http header都加上token
    let token = sessionStorage.getItem('Authorization');
    if (!config.headers.hasOwnProperty('Authorization') && token) {
      config.headers.Authorization = token;
    }
    // if(config.method === "post") {
      // config.data = qs.stringify(config.data, {arrayFormat: 'indices', allowDots: true});
      // config.data = JSON.stringify(config.data);
    //   console.log(config.data);
    // }
    return config;
  },
  error => {
    Message({
      showClose: true,
      message: error,
      type: "warning"
    });
    return Promise.reject(error);
  }
)

// response interceptor
instance.interceptors.response.use(
  response => {
    if (response.status === 200) {
      return Promise.resolve(response);
    } else {
      return Promise.reject(response);
    }
  },
  // error
  error => {
    if (error.response.status) {
      switch (error.response.status) {
        // 401: Not logged in
        case 401:
          router.replace({
            path: '/index',
            query: {
              redirect: router.currentRoute.fullPath
            }
          });
          break;

        // 403 token overdue
        case 403:
          Message({
            message: 'Please log in again',
            duration: 1000,
            forbidClick: true
          });
          // clear token
          localStorage.removeItem('token');
          store.commit('loginSuccess', null);
          // jump to Login
          setTimeout(() => {
            router.replace({
              path: '/index',
              query: {
                redirect: router.currentRoute.fullPath
              }
            });
          }, 1000);
          break;

        // 404 request does not exist
        case 404:
          Message({
            message: 'network does not exist',
            duration: 1500,
            forbidClick: true
          });
          break;

        // other error
        default:
          Message({
            message: error.response.data.message,
            duration: 1500,
            forbidClick: true
          });
        }
        return Promise.reject(error.response);
      }
  });

export default instance;
